/* $RCSFile: CrmInputOrder.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmInputOrder/CrmInputOrder.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:50  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Authentication;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmInputOrder
{

 	#region Local TraceSwitch 
	public class InputOrderTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("InputOrderTrace","Special Trace Switch for CrmInputOrder");
	}
	#endregion Local TraceSwitch 

    public class AStr
    {
        public const string CrmInputOrderOwner           =   "ORDER_INPUT_OWNER";
        public const string AssignToOwner                =   "ORDER_INPUT_OWNER_AUTOASSIGN";

        public const string AutoCustomer                 =   "ORDER_INPUT_CUSTOMER_AUTOASSIGN";
        public const string DefaultCustomer              =   "ORDER_INPUT_DEFAULT_CUSTOMER";

        public const string UseCustomerFilter            =   "ORDER_INPUT_USE_CUSTOMER_FILTER";
        public const string CustomerFilter               =   "ORDER_INPUT_CUSTOMER_FILTER";
        public const string UserQueryMode                =   "ORDER_INPUT_USERQUERY_MODE";
        public const string UserQuery                    =   "ORDER_INPUT_USERQUERY";

        public const string UseProductFilter             =   "ORDER_INPUT_USE_PRODUCT_FILTER";
        public const string ProductFilter                =   "ORDER_INPUT_PRODUCT_FILTER";
        public const string ProdUserQueryMode            =   "ORDER_INPUT_PROD_USERQUERY_MODE";
        public const string ProdUserQuery                =   "ORDER_INPUT_PROD_USERQUERY";


        public const string UseForcedPrice               =   "ORDER_INPUT_USE_FORCEDPRICE";
        public const string VAT                          =   "ORDER_INPUT_VAT";
        public const string UsePriceList                 =   "ORDER_INPUT_USEPRICELIST";
        public const string InputPriceList               =   "ORDER_INPUT_INPUTPRICELIST";
        public const string PriceList                    =   "ORDER_INPUT_PRICELIST";
    }
    /// <summary>
    /// Initializer class for CrmInputOrder 
    /// </summary>
    public class CrmInputOrderSI : PortalCRMModuleControlSI
    {
        public CrmInputOrderSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrderSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrderSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrderSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			// Specific parameters
            string extgrp                               =   pm.ExtendedResourcesGroup;
            
            SettingItemSpecial AttributeOwner           =   new SettingItemSpecial(AStr.AssignToOwner,new BooleanDataType());
            AttributeOwner.Required                     =   false;
            AttributeOwner.Value                        =   StStr.strFalse;
            AttributeOwner.Order                        =   10;
            AttributeOwner.ExtendedGroupName            =   extgrp;
            AttributeOwner.EnglishName                  =   "Assign to Owner";
            AttributeOwner.Description                  =   "When checked, the new orders will be automatically assigned to selected owner";
            bSettings.AddSetting(AttributeOwner);

            WSListDataType defAcc                       =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner              =   new SettingItemSpecial(AStr.CrmInputOrderOwner,defAcc);
            ADNDynSystemUser wsys                       =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName                       =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                                    =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                                    =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value                       =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue                 =   wsys.fullname;
            }
            ModuleOwner.EnglishName                     =   "Owner";
            ModuleOwner.Order                           =   20;
            ModuleOwner.ExtendedGroupName               =   extgrp;
            ModuleOwner.Description                     =   "Choose the owner for orders created with this module if previous checkbox checked";
            ModuleOwner.SettingItemsEvent               +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);

            // Use a fixed Customer, so don't select it from input
            SettingItemSpecial FixedCustomer            =   new SettingItemSpecial(AStr.AutoCustomer,new BooleanDataType());
            FixedCustomer.Required                      =   false;
            FixedCustomer.Value                         =   StStr.strFalse;
            FixedCustomer.Order                         =   22;
            FixedCustomer.ExtendedGroupName             =   extgrp;
            FixedCustomer.EnglishName                   =   "Don't input customer";
            FixedCustomer.Description                   =   "When checked, the customer will not be input but auto assigned to a predefined value entered in next setting";
            bSettings.AddSetting(FixedCustomer);

            defAcc                                      =   new WSListDataType(CrmStr.account,"name", "ID");
            defAcc.NeedDisplayTextEvent                 +=  new NeedDisplayTextEventHandler(DefaultCustomer4ORDER_NeedDisplayTextEvent);
	        SettingItemSpecial DefaultCustomer4Incident =   new SettingItemSpecial(AStr.DefaultCustomer,defAcc);
            defAcc.DisplayTextValue                     =   string.Empty;

            DefaultCustomer4Incident.Value              =   Guid.Empty.ToString(); // we need to set a default value even if not installed
            DefaultCustomer4Incident.Required           =   false;
            DefaultCustomer4Incident.Order              =   35;
            DefaultCustomer4Incident.ExtendedGroupName  =   extgrp;
            DefaultCustomer4Incident.EnglishName        =   "Default customer";
            DefaultCustomer4Incident.Description        =   "Select a default customer for orders";

            bSettings.AddSetting(DefaultCustomer4Incident);

            // to filter customers when input
            SettingItemSpecial UseCustomerFilter        =   new SettingItemSpecial(AStr.UseCustomerFilter,new BooleanDataType());
            UseCustomerFilter.Required                  =   false;
            UseCustomerFilter.Value                     =   StStr.strFalse;
            UseCustomerFilter.Order                     =   40;
            UseCustomerFilter.ExtendedGroupName         =   extgrp;
            UseCustomerFilter.EnglishName               =   "Filter Customer";
            UseCustomerFilter.Description               =   "When checked customers are filtered by next query.";
            bSettings.AddSetting(UseCustomerFilter);

            SettingItemSpecial FirstQueryMode           =   new SettingItemSpecial(AStr.UserQueryMode,new BooleanDataType());
            FirstQueryMode.Value                        =   StStr.strTrue;
            FirstQueryMode.Order                        =   50;
            FirstQueryMode.ExtendedGroupName            =   extgrp;
            FirstQueryMode.EnglishName                  =   "Use Xml request";
            FirstQueryMode.Description                  =   "If checked use Fetch Xml request else use a saved user query.";
            bSettings.AddSetting(FirstQueryMode);

            CustomListDataType gdt                      =   new CustomListDataType(null,CrmStr.name,CrmStr.userqueryid);
            gdt.CrmEntity                               =   CrmStr.account;
            gdt.NeedDataEvent                           +=  new NeedDataEventHandler(CrmHelper.BuildAccountQueryTable);

            SettingItemSpecial FirstQuery               =   new SettingItemSpecial(AStr.UserQuery,gdt);
            FirstQuery.Value                            =   string.Empty;
            FirstQuery.Order                            =   60;
            FirstQuery.ExtendedGroupName                =   extgrp;
            FirstQuery.EnglishName                      =   "Customer User Query";
            FirstQuery.Description                      =   "Select the Customer query";
            bSettings.AddSetting(FirstQuery);

            SettingItemSpecial FirstQueryXml            =   new SettingItemSpecial(AStr.CustomerFilter,new StringDataType(10));
            FirstQueryXml.Order                         =   70;
            FirstQueryXml.ExtendedGroupName             =   extgrp;
            FirstQueryXml.EnglishName                   =   "Fetch Xml for Query";
            FirstQueryXml.Description                   =   "Enter the Fetch XML content for customers query";
            bSettings.AddSetting(FirstQueryXml);

        
            // to filter products when input
            SettingItemSpecial UseProductFilter         =   new SettingItemSpecial(AStr.UseProductFilter,new BooleanDataType());
            UseProductFilter.Required                   =   false;
            UseProductFilter.Value                      =   StStr.strFalse;
            UseProductFilter.Order                      =   80;
            UseProductFilter.ExtendedGroupName          =   extgrp;
            UseProductFilter.EnglishName                =   "Filter Products";
            UseProductFilter.Description                =   "When checked Products list is filtered.";
            bSettings.AddSetting(UseProductFilter);

            SettingItemSpecial ProdQueryMode            =   new SettingItemSpecial(AStr.ProdUserQueryMode,new BooleanDataType());
            ProdQueryMode.Value                         =   StStr.strTrue;
            ProdQueryMode.Order                         =   90;
            ProdQueryMode.ExtendedGroupName             =   extgrp;
            ProdQueryMode.EnglishName                   =   "Use Xml request to filter";
            ProdQueryMode.Description                   =   "If checked use Fetch Xml request else use a saved user query.";
            bSettings.AddSetting(ProdQueryMode);

            CustomListDataType gdt1                     =   new CustomListDataType(null,CrmStr.name,CrmStr.userqueryid);
            gdt1.CrmEntity                              =   CrmStr.product;
            gdt1.NeedDataEvent                          +=  new NeedDataEventHandler(CrmHelper.BuildQueryTable);

            SettingItemSpecial ProdUserQuery            =   new SettingItemSpecial(AStr.ProdUserQuery,gdt1);
            ProdUserQuery.Value                         =   string.Empty;
            ProdUserQuery.Order                         =   100;
            ProdUserQuery.ExtendedGroupName             =   extgrp;
            ProdUserQuery.EnglishName                   =   "Product query";
            ProdUserQuery.Description                   =   "Select the product query";
            bSettings.AddSetting(ProdUserQuery);

            SettingItemSpecial ProductQueryXml          =   new SettingItemSpecial(AStr.ProductFilter,new StringDataType(10));
            ProductQueryXml.Order                       =   110;
            ProductQueryXml.ExtendedGroupName           =   extgrp;
            ProductQueryXml.EnglishName                 =   "Product Fetch Xml for Query";
            ProductQueryXml.Description                 =   "Enter the XML content for Products query";
            bSettings.AddSetting(ProductQueryXml);
        
            SettingItemSpecial UseForcedPrice           =   new SettingItemSpecial(AStr.UseForcedPrice,new BooleanDataType());
            UseForcedPrice.Value                        =   StStr.strFalse;
            UseForcedPrice.Order                        =   120;
            UseForcedPrice.ExtendedGroupName            =   extgrp;
            UseForcedPrice.EnglishName                  =   "Use forced price";
            UseForcedPrice.Description                  =   "If checked enable using forced price.";
            bSettings.AddSetting(UseForcedPrice);
        
            DecimalDataType VatInput                    =   new DecimalDataType();
            SettingItemSpecial SellingCountryVAT        =   new SettingItemSpecial(AStr.VAT,VatInput);
            SellingCountryVAT.Value                     =   "0";
            SellingCountryVAT.Order                     =   130;
            SellingCountryVAT.ExtendedGroupName         =   extgrp;
            SellingCountryVAT.EnglishName               =   "VAT Rate";
            SellingCountryVAT.Description               =   "Input the VAT rate to use, zero for no VAT in order.";
            bSettings.AddSetting(SellingCountryVAT);

            SettingItemSpecial UsePriceList             =   new SettingItemSpecial(AStr.UsePriceList,new BooleanDataType());
            UsePriceList.Value                          =   StStr.strFalse;
            UsePriceList.Order                          =   140;
            UsePriceList.ExtendedGroupName              =   extgrp;
            UsePriceList.EnglishName                    =   "Use price list";
            UsePriceList.Description                    =   "If checked use price list else use default product price.";
            bSettings.AddSetting(UsePriceList);
            
            SettingItemSpecial InputPriceList           =   new SettingItemSpecial(AStr.InputPriceList,new BooleanDataType());
            InputPriceList.Value                        =   StStr.strFalse;
            InputPriceList.Order                        =   145;
            InputPriceList.ExtendedGroupName            =   extgrp;
            InputPriceList.EnglishName                  =   "Input price list";
            InputPriceList.Description                  =   "If checked let user input price list.";
            bSettings.AddSetting(InputPriceList);

            CurrencyDataType plv                        =   new CurrencyDataType(true,false,0);
            plv.NeedDataEvent                           +=  new NeedDataEventHandler(CrmHelper.GetTransactionCurrencies);
            SettingItemSpecial CurrencyPriceList	    =	new SettingItemSpecial(AStr.PriceList,plv);
	        CurrencyPriceList.Required			        =	false;
	        CurrencyPriceList.Order					    =	150;
            SellingCountryVAT.ExtendedGroupName         =   extgrp;
	        CurrencyPriceList.EnglishName			    =	"Currency / Price List";
	        CurrencyPriceList.Description			    =	"Select a currency and its associated price list";
	        bSettings.AddSetting(CurrencyPriceList);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrderSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Called by the webService RadCombo to display some text
        /// </summary>
        void DefaultCustomer4ORDER_NeedDisplayTextEvent(object sender,WSListEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrderSI DefaultCustomer4ORDER_NeedDisplayTextEvent Guid: {0}", e.Val),InputOrderTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Val);
            if ( custId == Guid.Empty )
                return;
            DynEntity dynac                 =   null;
            switch ( e.entityName )
            {
                case CrmStr.account:
                dynac                       =   new ADNDynAccount(Wrapper,custId);
                break;
                case CrmStr.contact:
                dynac                       =   new ADNDynContact(Wrapper,custId);
                break;
                default:
                return;
            }
            dynac.adminRetrieve();
            WSListDataType defAcc           =   (WSListDataType )sender;
            switch ( e.entityName )
            {
                case CrmStr.account:
                    defAcc.DisplayTextValue =   dynac.name;
                break;
                case CrmStr.contact:
                    defAcc.DisplayTextValue =   dynac.fullname;
                break;
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrderSI DefaultCustomer4ORDER_NeedDisplayTextEvent END name: {0}", dynac.name),InputOrderTrace.Sw.Info);
        }

        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrderSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),InputOrderTrace.Sw.Info);
            Guid custId                 =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac      =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc       =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue     =   dynac.fullname;
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrderSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),InputOrderTrace.Sw.Info);
        }
    }

    public partial class CrmInputOrder : PortalCRMModuleControl
    {
        #region General implementation

        public override Guid GuidID
        {
            get
            {
                return new Guid("{0919E406-3478-40c8-B5DE-23DB9F8A998B}");
            }
        }
        #endregion General implementation

        #region Properties

        public bool ShowPriceList      
        {
            get
            {
                return Settings[AStr.InputPriceList].ToBool();
            }
        }

        public bool isTotalTaxesVisible
        {
            get
            {
                return ( Settings[AStr.VAT].ToDecimal() != 0m );
            }
        }
            
        public bool isDiscountVisible
        {
            get
            {
                return Settings[AStr.UseForcedPrice].ToBool();
            }
        }
        
        string _cSymbol                             =   string.Empty;
        public string currencyFormat(int nbdecimal)
        {
            if ( string.IsNullOrEmpty(_cSymbol) )
            {
                string strGuid                      =   string.Empty;
                if ( !ShowPriceList )
                {
                    strGuid                         =   Settings[AStr.PriceList].ToString().Trim();
                    string[] v                      =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if ( ( v.Length >= 2 ) && !string.IsNullOrEmpty(v[0]) )
                    {
                        strGuid                     =   v[0];
                    }
                }
                else
                {
                    strGuid                         =   PricingChooser.SelectedItem;
                    string[] v                      =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if ( ( v.Length >= 2 ) && !string.IsNullOrEmpty(v[0]) )
                    {
                        strGuid                     =   v[0];
                    }
                }
                Guid CurrencyID                    =   new Guid(strGuid);
                ADNDynTransactionCurrency DefaultCurrency   =   new ADNDynTransactionCurrency(Wrapper,CurrencyID);
                DefaultCurrency.adminRetrieve();
                _cSymbol                        =   DefaultCurrency.currencysymbol;
            }
		    if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder currencyFormat GET currencysymbol: {0}",_cSymbol),InputOrderTrace.Sw.Info);
            string currencyFormat               =   string.Format("{{0:{0} ###,###.#0;;0.00}}", _cSymbol);
            switch(nbdecimal)
            {
                case 0:
                currencyFormat               =   string.Format("{{0:{0} ###,###;;0}}", _cSymbol);
                break;
                case 1:
                currencyFormat               =   string.Format("{{0:{0} ###,###.#;;0.0}}", _cSymbol);
                break;
                case 2:
                currencyFormat               =   string.Format("{{0:{0} ###,###.#0;;0.00}}", _cSymbol);
                break;
                case 3:
                currencyFormat               =   string.Format("{{0:{0} ###,###.##0;;0.000}}",_cSymbol);
                break;
                case 4:
                currencyFormat               =   string.Format("{{0:{0} ###,###.###0;;0.0000}}", _cSymbol);
                break;
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder currencyFormat GET END Format: '{0}'.",currencyFormat),InputOrderTrace.Sw.Info);
            return currencyFormat;
        }

        #endregion Properties


        /// <summary>
        /// Ctor
        /// </summary>
        public CrmInputOrder()
        {
            if ( InputOrderTrace.Sw.TraceVerbose | ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder Ctor BEG.",(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup         =   "Main";
            if ( InputOrderTrace.Sw.TraceVerbose | ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder Ctor END.",(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                         =   "INPUTCRMORDER";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmInputOrderSI(bSettings,this);
        }

        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder Page_Load isPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            if ( !IsPostBack )
            {
                if ( Settings[AStr.UsePriceList].ToBool() )
                {
                    string strGuid                      =   string.Empty;
                    if ( !ShowPriceList )
                    {
                        PricingChooser.Visible          =   false;
                        LblPriceList.Visible            =   false;
                        strGuid                         =   Settings[AStr.PriceList].ToString().Trim();
                        string[] v                      =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        if ( ( v.Length >= 2 ) && !string.IsNullOrEmpty(v[1]) )
                        {
                            strGuid                     =   v[1];
                        }
                    }
                    else
                    {
                        LblPriceList.Visible            =   false;
                        PricingChooser.Visible          =   true;
                        Guid SelectedGuid               =   Guid.Empty;
                        SortedList<string,ADNDynTransactionCurrency> currencyList   =   CrmHelper.GetTransactionCurrencies0(ref SelectedGuid);
                        PricingChooser.CurrencyList     =   currencyList;
                        PricingChooser.DataBind();
                        strGuid                         =   PricingChooser.SelectedItem;
                        string[] v                      =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        if ( ( v.Length >= 2 ) && !string.IsNullOrEmpty(v[1]) )
                        {
                            strGuid                     =   v[1];
                        }
                    }
                    Guid PriceListID                    =   new Guid(strGuid);
                    // Try to get product pricelist
                    ADNDynPricelevel pl                 =   new ADNDynPricelevel(Wrapper,PriceListID);
                    if ( pl.adminRetrieve() )
                    {
                        LblCurrency.Text                =   pl.transactioncurrencyName;
                    }
                }
                else
                {
                    PricingChooser.Visible              =   false;
                    LblPriceList.Visible                =   false;
                    LblCurrencyLbl.Visible              =   false;
        
                }
                string DataFormatString                                                                     =   currencyFormat(2);
                ((GridNumericColumn)RadGrid1.Columns.FindByDataField("Price")).DataFormatString             =   DataFormatString;
                ((GridNumericColumn)RadGrid1.Columns.FindByDataField("Total")).DataFormatString             =   DataFormatString;
                ((GridNumericColumn)RadGrid1.Columns.FindByDataField("TotalTaxes")).DataFormatString        =   DataFormatString;
                ((GridCalculatedColumn)RadGrid1.Columns.FindByUniqueName("GrandTotal")).DataFormatString    =   DataFormatString;
            }
        }


        #region insert input in Crm

        /// <summary>
        /// Tasks to do:
        /// 0) validate datas
        /// 1) Insert record in CRM
        /// 2) insert record in DB
        /// </summary>
        void CrmInputOrder_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (InputOrderTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmInputOrder CrmInputOrder_ADNUpdateModule BEG.",InputOrderTrace.Sw.Info);
            bool autoAssignCustomer                 =   Settings[AStr.AutoCustomer].ToBool();
            if ( !autoAssignCustomer && string.IsNullOrEmpty(ComboCustomer.SelectedValue)  )
            {
                if (InputOrderTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmInputOrder CrmInputOrder_ADNUpdateModule canceled: no selectedCustomer.",InputOrderTrace.Sw.Info);
                LblError.Text                       =   LocalizeHelper.Localize("ORDER_INPUT_ERROR_CUSTOMER","Customer is required");
                e.Cancel                            =   true;
                return;
            }
            // Add new Order
            ADNDynSalesOrder CrmOrder               =   new ADNDynSalesOrder(Wrapper,TbOrderTitle.Text.Trim());
            List<DynEntity> childs                  =   new List<DynEntity>();
            bool UseForcedPrice                     =   Settings[AStr.UseForcedPrice].ToBool();


            // Get the price list from settings
            Guid PriceListID                        =   Guid.Empty;
            string strGuid                          =   string.Empty;
            if ( !ShowPriceList )
            {
                strGuid                             =   Settings[AStr.PriceList].ToString().Trim();
                string[] v                          =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (v.Length >= 2)
                    strGuid                         =   v[1];
            }
            else
            {
                strGuid                             =   PricingChooser.SelectedItem;
                string[] v                          =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (v.Length >= 2)
                    strGuid                         =   v[1];
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule PriceListID: '{0}'.",strGuid),InputOrderTrace.Sw.Info);
            if ( !string.IsNullOrEmpty(strGuid) )
                  PriceListID                       =   new Guid(strGuid);
            try
            {
                foreach (DataRow rw in makeT.Rows)
                {
                    Guid productid                  =   (Guid)rw["ProductID"];
                    if ( productid == Guid.Empty )
                        continue;
                    ADNDynSalesOrderDetail detail   =   new ADNDynSalesOrderDetail(Wrapper);
                    detail.SetOwnerFromUserId();
                    detail.quantity                 =   (decimal)rw["Quantity"];
                    decimal tax                     =   (decimal)rw["TotalTaxes"];
                    detail.tax                      =   tax;
                    decimal baseamount              =   (decimal)rw["Total"];
                    detail.baseamount               =   baseamount;
                    decimal manualdiscountamount    =   (decimal)rw["Discount"]; // here we force discount in manual discount, else it will be reevaluated by crm
                    detail.manualdiscountamount     =   manualdiscountamount; // here we force discount in manual discount, else it will be reevaluated by crm
                    detail.extendedamount           =   (baseamount >= manualdiscountamount) ? (baseamount-manualdiscountamount)+tax:0m;
                    detail.ispriceoverridden        =   UseForcedPrice;
                    detail.productid                =   productid; // We can't set productid and productdescription together
                    detail.uomid                    =   (Guid)rw["uomid"];// We can't set uomid and productdescription together
                    if ( UseForcedPrice )
                    {
                        ADNDynProduct prod          =   new ADNDynProduct(Wrapper,productid);
                        if ( prod.adminRetrieve() )
                        {
                            //detail.productdescription = prod.name;
                            // If not using pricelist return default price
                            if ( !Settings[AStr.UsePriceList].ToBool() )
                            {
                                PriceListID         =   prod.pricelevelid;
                            }
                        }
                        detail.priceperunit         =   (decimal)rw["Price"];
                    }

                    childs.Add(detail);
                }
                if ( PriceListID != Guid.Empty )
                    CrmOrder.pricelevelid           =   PriceListID;

                if (InputOrderTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule ComboCustomer.SelectedValue: '{0}'.",ComboCustomer.SelectedValue.ToString()),InputOrderTrace.Sw.Info);
                if ( !autoAssignCustomer )
                {
                    if ( string.IsNullOrEmpty(ComboCustomer.SelectedValue)  )
                    {
                        CrmOrder.customerid         =   Guid.Empty;
                        // If the Company Name is not empty checks the existence of the company
                        string searchedCustomer     =   ComboCustomer.Text.Trim();
                        bool parentCreated          =   false;
                        if ( InputOrderTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule searching for Customer: '{0}'.",searchedCustomer),InputOrderTrace.Sw.Info);
                        if ( searchedCustomer != string.Empty )
                        {
                            ADNDynAccount s         =   Wrapper.Util.FindAccountByName(searchedCustomer,true,ref parentCreated);
                            if ( s != null )
                                CrmOrder.customerid =   s.accountid;
                            else
                            {
                                e.Cancel            =   true;
                                return;
                            }
                        }

                    }
                    else CrmOrder.customerid                =   new Guid(ComboCustomer.SelectedValue);
                }
                else //autoAssignCustomer
                {
                    Guid defaultCustomerId                  =   Settings[AStr.DefaultCustomer].ToGuid();
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule usr defaultCustomerId: {0}",defaultCustomerId),InputOrderTrace.Sw.Info);
                    if ( Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms )
                    {
                        AddonNiceMembershipUser usr         =   (AddonNiceMembershipUser)Membership.GetUser(PortalSettings.CurrentIdentity.Name);
                        if ( InputOrderTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule usr null: {0}",(usr == null)),InputOrderTrace.Sw.Info);
                        if ( usr != null )
                        {
                            CrmOrder.DefaultCustomerName    =   usr.CustomerId.typeName;
                            CrmOrder.customerid             =   usr.CustomerId.CrmId;
                            if ( InputOrderTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule order assigned to typeName: {0}', id: {1}.",
                                    usr.CustomerId.typeName,usr.CustomerId.CrmId),InputOrderTrace.Sw.Info);
                        }
                        else
                        {
                            CrmOrder.DefaultCustomerName    =   CrmStr.account;
                            CrmOrder.customerid             =   defaultCustomerId;
                        }
                    }
                    else // TBD: transfer default assign account from E-Commerce to main portal and use it
                    {
                        CrmOrder.DefaultCustomerName        =   CrmStr.contact;
                        CrmOrder.customerid                 =   defaultCustomerId;
                    }
                }
                if (InputOrderTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule Before save CrmOrder.customerid: '{0}'",CrmOrder.customerid),InputOrderTrace.Sw.Info);
                Guid OrderID                                =   CrmOrder.Save(childs);
                LblOrderNumber.Text                         =   CrmOrder.ordernumber;
                if (InputOrderTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule ordernumber: '{0}'",CrmOrder.ordernumber),InputOrderTrace.Sw.Info);
            }
            catch (Exception ex)
            {
                if (InputOrderTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputOrder CrmInputOrder_ADNUpdateModule Adding Order ex :{0}", ex),InputOrderTrace.Sw.Info);
                throw;
            }

            bool autoAssign                                 =   Settings[AStr.AssignToOwner].ToBool();
                if (InputOrderTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule autoAssign: {0}",autoAssign),InputOrderTrace.Sw.Info);
            // Assign to default owner
            if ( autoAssign )
            {
                try
                {
                    string str                  =   Settings[AStr.CrmInputOrderOwner].Value;
                    if (InputOrderTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule  assigning Incident to owner id: '{0}'", str),InputOrderTrace.Sw.Info);
                    CrmOrder.adminAssign(new Guid(str));
                    if (InputOrderTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder CrmInputOrder_ADNUpdateModule Incident assigned to owner id: '{0}'", str),InputOrderTrace.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (InputOrderTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputOrder CrmInputOrder_ADNUpdateModule assigning Incident ex :{0}", ex),InputOrderTrace.Sw.Info);
                    throw;
                }
            }
            if (InputOrderTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmInputOrder CrmInputOrder_ADNUpdateModule END.",InputOrderTrace.Sw.Info);
        }
        
        /// <summary>
        /// re-initialized fields 
        /// </summary>
        protected void clean()
        {
            ComboCustomer.ClearSelection();
            TbOrderTitle.Text           =   string.Empty;
            LblOrderNumber.Text         =   string.Empty;
            ComboCustomer.Text          =   string.Empty;
            makeT                       =   null;
            RadGrid1.Rebind();
        }

        #endregion insert input in Crm

        #region radCombobox load handlers

        /*
        void LoadPickList(string pickListName,RadComboBox Combo)
        {
            string entityNm                 =   CrmStr.incident;
            if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadPickList BEG entityNm: '{0}'.",
                    entityNm),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            try
            {
                string pickListDisplayName  =   Wrapper.Util.ExtractAttributeDisplayName(entityNm,pickListName);
                ArrayList Arl               =   GetPickListArray(pickListName,entityNm);
                Combo.DataTextField         =   "name";
                Combo.DataValueField        =   "val";
                Combo.DataSource            =   Arl;
                Combo.DataBind();
                foreach (RadComboBoxItem item in Combo.Items)
                {
                    item.ToolTip            =   item.Text;
                }
            }
            catch (Exception ex)
            {
                    if (InputOrderTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputOrder LoadPickList ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadPickList END Count: {0}",
                    Combo.Items.Count),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
        */

        void LoadLookup(string entityName, RadComboBox Combo,InternalConditionExpression c1)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder LoadLookup BEG.",InputOrderTrace.Sw.Info);
            Guid firstEntity        =   Guid.Empty;
            ArrayList ar            =   Wrapper.Util.PotentialEntities(entityName,c1,ref firstEntity,false);
            Combo.DataTextField     =   "name";
            Combo.DataValueField    =   "ID";
            Combo.DataSource        =   ar;
            Combo.DataBind();
            if ( firstEntity != Guid.Empty )
                Combo.SelectedValue =   firstEntity.ToString();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadLookup END Count: {0}.",Combo.Items.Count),InputOrderTrace.Sw.Info);
        }

        void LoadCustomers()
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder LoadCustomers BEG.",InputOrderTrace.Sw.Info);
            try
            {
                if (!Settings[AStr.UseCustomerFilter].ToBool())
                    LoadLookup(CrmStr.account, ComboCustomer, null);
                else
                {
                    DataTable Tb                        =   null;
                    if (!Settings[AStr.UserQueryMode].ToBool())
                    {
                        string FetchXml                 =   Settings[AStr.CustomerFilter].Value;
                        string entityName               =   string.Empty;
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadCustomers FetchXml: {0}",
                                FetchXml),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                              =   Wrapper.Util.GetTableFromFetchXmlQuery(ResetWrapper,FetchXml,ref entityName,CrmStr.name,string.Empty,string.Empty,0,true);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadCustomers FentityName: {0}, Count: {1}",
                                entityName,(Tb!=null) ? Tb.Rows.Count:0),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    else 
                    {
                        Guid QueryId                    =   new Guid(Settings[AStr.UserQuery].Value);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadCustomers QueryId: {0}",
                                QueryId),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                              =   Wrapper.Util.GetTableFromQuery(QueryId,ResetWrapper,true);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadCustomers Count: {0}",
                                (Tb!=null) ? Tb.Rows.Count:0),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    if ( Tb != null )
                    {
                        ComboCustomer.DataTextField     =   CrmStr.name;
                        ComboCustomer.DataValueField    =   CrmStr.accountid;
                        ComboCustomer.DataSource        =   Tb;
                        ComboCustomer.DataBind();
                    }

                }
            }
            catch (Exception ex)
            {
                    if (InputOrderTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputOrder LoadCustomers ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadCustomers END Count: {0}",
                    ComboCustomer.Items.Count),InputOrderTrace.Sw.Info);
        }

        void ComboCustomer_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs  e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder ComboCustomer_ItemsRequested BEG.",InputOrderTrace.Sw.Info);
            LoadCustomers();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder ComboCustomer_ItemsRequested END.",InputOrderTrace.Sw.Info);
        }

        void LoadProducts(RadComboBox comboProd)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder LoadProducts BEG.",InputOrderTrace.Sw.Info);
            try
            {
                if (!Settings[AStr.UseProductFilter].ToBool())
                    LoadLookup(CrmStr.product, comboProd, null);
                else
                {
                    DataTable Tb                =   null;
                    if (!Settings[AStr.ProdUserQueryMode].ToBool())
                    {
                        string FetchXml             =   Settings[AStr.ProductFilter].Value;
                        string entityName           =   string.Empty;
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadProducts FetchXml: {0}",
                                FetchXml),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                          =   Wrapper.Util.GetTableFromFetchXmlQuery(ResetWrapper,FetchXml,ref entityName,CrmStr.name,string.Empty,string.Empty,0,true);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadProducts FentityName: {0}, Count: {1}",
                                entityName,(Tb!=null) ? Tb.Rows.Count:0),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    else 
                    {
                        Guid QueryId                =   new Guid(Settings[AStr.ProdUserQuery].Value);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadProducts QueryId: {0}",
                                QueryId),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                        Tb                          =   Wrapper.Util.GetTableFromQuery(QueryId,ResetWrapper,true);
                        if (InputOrderTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadProducts Count: {0}",
                                (Tb!=null) ? Tb.Rows.Count:0),(InputOrderTrace.Sw.TraceVerbose)? InputOrderTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                    }
                    if ( Tb != null )
                    {
                        comboProd.DataTextField     =   CrmStr.name;
                        comboProd.DataValueField    =   CrmStr.productid;
                        comboProd.DataSource        =   Tb;
                        comboProd.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                    if (InputOrderTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputOrder LoadProducts ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder LoadProducts END Count: {0}",
                    comboProd.Items.Count),InputOrderTrace.Sw.Info);
        }

        void cbProduct_ItemsRequested(object o,RadComboBoxItemsRequestedEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder cbProduct_ItemsRequested BEG.",InputOrderTrace.Sw.Info);
            RadComboBox comboprod           =   (RadComboBox)o;
            LoadProducts(comboprod);
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder cbProduct_ItemsRequested END.",InputOrderTrace.Sw.Info);
        }
        
        #endregion radCombobox load handlers

        #region radGrid workspace
        
        DataTable makeT
        {
            get
            {
                if ( InputOrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( "[V]CrmInputOrder makeT GET BEG.",InputOrderTrace.Sw.Info);
                if ( ViewState["MakeT"] != null )
                    return (DataTable)ViewState["MakeT"];
                DataTable tb        =   new DataTable();
                tb.Columns.Add("Product",typeof(string));
                DataColumn c        =   tb.Columns.Add("LineID",typeof(int));
                tb.Columns.Add("ProductID",typeof(Guid));
                tb.Columns.Add("uomid",typeof(Guid));
                tb.Columns.Add("Price",typeof(decimal));
                tb.Columns.Add("Quantity",typeof(decimal));
                tb.Columns.Add("Total",typeof(decimal));
                tb.Columns.Add("Discount",typeof(decimal));
                tb.Columns.Add("TotalTaxes",typeof(decimal));
                tb.PrimaryKey       =   new DataColumn[]{c};
                // Add a first empty row, user must select a product
                AddOrderItem(tb,string.Empty,Guid.Empty);
                
                ViewState["MakeT"]  =   tb;
                if ( InputOrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( "[V]CrmInputOrder makeT GET END.",InputOrderTrace.Sw.Info);
                return tb;
            }
            set
            {
                ViewState["MakeT"] = value;
            }
        }

        protected void RadGrid1_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_NeedDataSource BEG.",InputOrderTrace.Sw.Info);
            RadGrid1.DataSource     =    makeT;
        }

        decimal totalDiscount   =   0m;
        decimal totalQuantity   =   0m;
        void RadGrid1_ItemDataBound(object sender,GridItemEventArgs e)
        {
            bool isGridDataItem                         =   ( e.Item is GridDataItem );
            bool isGridEditableItem                     =   ( e.Item is GridEditableItem );
            bool isGridFooterItem                       =   ( e.Item is GridFooterItem );
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder RadGrid1_ItemDataBound BEG isGridDataItem: {0}, isGridEditableItem: {1}, isGridFooterItem: {2}.",
                    isGridDataItem,isGridEditableItem,isGridFooterItem),InputOrderTrace.Sw.Info);
            if ( !isGridDataItem  && !isGridEditableItem && !isGridFooterItem )
                    return;
            if ( isGridFooterItem )
            {
                GridFooterItem footerItem               =   (GridFooterItem)e.Item;
                string DataFormatString                 =   currencyFormat(2);

                footerItem["Discount"].Text             =   "Total: " + totalDiscount.ToString(DataFormatString);
                footerItem["Quantity"].Text             =   "Sum: " + totalQuantity.ToString(DataFormatString);
            }
            else if ( isGridDataItem )
            {
                GridDataItem editedItem                 =   e.Item as GridDataItem;
                RadComboBox cbProduct                   =   ((RadComboBox)editedItem.FindControl("RadComboProduct"));
                bool Okproduct                          =   ( cbProduct != null );
                int LineID                              =   Convert.ToInt32(editedItem.GetDataKeyValue("LineID"));
                DataRow drw                             =   makeT.Rows.Find(LineID);
                if ( InputOrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder RadGrid1_ItemDataBound Okproduct: {0}, LineID: {1}, rw found: {2}.",
                        Okproduct,LineID,drw != null),InputOrderTrace.Sw.Info);
                if ( Okproduct && ( drw != null ) )
                {
                    string name                         =   (string)drw["Product"];
                    cbProduct.Text                      =   name;
                    totalDiscount                       =   totalDiscount+(decimal)drw["Discount"];
                    totalQuantity                       =   totalQuantity+(decimal)drw["Quantity"];
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder RadGrid1_ItemDataBound name: {0}, totalDiscount: {1}, totalQuantity: {2}.",
                            name,totalDiscount,totalQuantity),InputOrderTrace.Sw.Info);
                }
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemDataBound END.",InputOrderTrace.Sw.Info);
        }


        void RadGrid1_ItemCreated(object sender,GridItemEventArgs e)
        {
            bool isGridDataItem                         =   ( e.Item is GridDataItem );
            bool isGridEditableItem                     =   ( e.Item is GridEditableItem );
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder RadGrid1_ItemCreated BEG isGridDataItem: {0}, isGridEditableItem: {1}.",
                    isGridDataItem,isGridEditableItem),InputOrderTrace.Sw.Info);
            if ( !isGridDataItem  && ! isGridEditableItem )
                    return;
            if ( isGridDataItem )
            {
                GridDataItem editedItem                 =   e.Item as GridDataItem;
                RadComboBox cbProduct                   =   ((RadComboBox)editedItem.FindControl("RadComboProduct"));
                if ( cbProduct != null )
                {
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemCreated found cbProduct.",InputOrderTrace.Sw.Info);
                    cbProduct.EnableLoadOnDemand        =   true;
                    cbProduct.ItemsRequested           +=   new RadComboBoxItemsRequestedEventHandler(cbProduct_ItemsRequested);
                    cbProduct.SelectedIndexChanged     +=   new RadComboBoxSelectedIndexChangedEventHandler(cbProduct_SelectedIndexChanged);
                    cbProduct.AutoPostBack              =   true;
                }
                RadNumericTextBox tbQuantity            =   (RadNumericTextBox)editedItem.FindControl("TbQuantity");
                if ( tbQuantity != null )
                {
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemCreated found tbQuantity.",InputOrderTrace.Sw.Info);
                    tbQuantity.TextChanged              +=  new EventHandler(tbQuantity_TextChanged);
                    tbQuantity.AutoPostBack             =   true;
                }
                RadNumericTextBox tbDiscount            =   (RadNumericTextBox)editedItem.FindControl("TbDiscount");
                if ( tbDiscount != null )
                {
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemCreated found tbDiscount.",InputOrderTrace.Sw.Info);
                    tbDiscount.TextChanged              +=  new EventHandler(tbDiscount_TextChanged);
                    tbDiscount.AutoPostBack             =   true;
                }
            }
            else
            {
                GridEditableItem editedItem             =   e.Item as GridEditableItem;
                RadComboBox cbProduct                   =   ((RadComboBox)editedItem.FindControl("RadComboProduct"));
                if ( cbProduct != null )
                {
                    if ( InputOrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemCreated found cbProduct.",InputOrderTrace.Sw.Info);
                    cbProduct.EnableLoadOnDemand        =   true;
                    cbProduct.ItemsRequested           +=   new RadComboBoxItemsRequestedEventHandler(cbProduct_ItemsRequested);
                    //cbProduct.SelectedIndexChanged     +=   new RadComboBoxSelectedIndexChangedEventHandler(cbProduct_SelectedIndexChanged);
                    //cbProduct.AutoPostBack              =   true;
                }
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_ItemCreated END.",InputOrderTrace.Sw.Info);
        }

        bool GetPrice(Guid ProductID,ref decimal price,ref Guid uomid,ref int nbdecimal,ref bool whole)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder GetPrice BEG ProductID: {0}, ShowPriceList: {1}.",
                    ProductID,ShowPriceList),InputOrderTrace.Sw.Info);
            ADNDynProduct prod              =   new ADNDynProduct(Wrapper,ProductID);
            if ( !prod.adminRetrieve() )
                return false;
            nbdecimal                       =   prod.quantitydecimal;
            uomid                           =   prod.defaultuomid;
            // If not using pricelist return default price
            if ( !Settings[AStr.UsePriceList].ToBool() )
            {
                price                       =   prod.price;
                return true;
            }
            // Get the price list from settings
            string strGuid                  =   string.Empty;
            if ( !ShowPriceList )
            {
                strGuid                     =   Settings[AStr.PriceList].ToString().Trim();
                string[] v                  =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (v.Length < 2)
                    return false;
                strGuid                     =   v[1];
            }
            else
            {
                strGuid                     =   PricingChooser.SelectedItem;
                string[] v                  =   strGuid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (v.Length < 2)
                    return false;
                strGuid                     =   v[1];
            }
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder GetPrice BEG strGuid: {0}.",strGuid),InputOrderTrace.Sw.Info);
            if ( string.IsNullOrEmpty(strGuid) )
                    return false;
            Guid PriceListID                =   new Guid(strGuid);
            // Try to get product pricelist
            ADNDynProductPricelevel pprod   =   ADNDynProductPricelevel.FindByPricelevelProduct(Wrapper,null,PriceListID,ProductID,prod.defaultuomid,true);
            if ( pprod == null )
                return false;
            price                           =   pprod.amount;
            string currency                 =   pprod.transactioncurrencyName;
            whole                           =   (pprod.quantitysellingcode == 1 );
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder GetPrice END.",InputOrderTrace.Sw.Info);
            return true;
        }

        bool AddOrderItem(DataTable ordersTable,string name,Guid ProductID)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmInputOrder AddOrderItem BEG name: {0}, ProductID: {1}",name,ProductID),InputOrderTrace.Sw.Info);
            DataRow newRow              =   ordersTable.NewRow();

            //As this example demonstrates only in-memory editing, a new primary key value should be generated
            //This should not be applied when updating directly the database
            DataRow[] allValues         =   ordersTable.Select(string.Empty,"LineID",DataViewRowState.CurrentRows);
            if ( allValues.Length > 0 )
            {
                newRow["LineID"]        =   (int)allValues[allValues.Length - 1]["LineID"] + 1;
            }
            else
            {
                newRow["LineID"]        =   1; //the table is empty;
            }
            newRow["Product"]           =   name;
            newRow["ProductID"]         =   ProductID;
            decimal price               =   0m;
            int nbdecimal               =   2;
            bool whole                  =   false;
            if ( ProductID != Guid.Empty )
            {
                Guid uomid              =   Guid.Empty;
                if ( GetPrice(ProductID,ref price,ref uomid,ref nbdecimal,ref whole) )
                    newRow["uomid"]     =   uomid;

            }
            newRow["Price"]             =   price;
            newRow["Quantity"]          =   1m;
            newRow["Total"]             =   price;
            newRow["Discount"]          =   0m;
            newRow["TotalTaxes"]        =   0m;

            ordersTable.Rows.Add(newRow);
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder AddOrderItem END.",InputOrderTrace.Sw.Info);
            return true;
        }

        /// <summary>
        /// Delete an order line
        /// </summary>
        void RadGrid1_DeleteCommand(object source,GridCommandEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_DeleteCommand BEG.",InputOrderTrace.Sw.Info);
            GridEditableItem item           =   e.Item as GridEditableItem;
            DataTable ordersTable           =   makeT;
            int LineID                      =   (int)RadGrid1.MasterTableView.DataKeyValues[item.ItemIndex]["LineID"];
            DataRow rw                      =   ordersTable.Rows.Find(LineID);
            ordersTable.Rows.Remove(rw);
            // Renumbers rows
            foreach ( DataRow rx in ordersTable.Rows )
            {
                int i                       =   (int)rx["LineID"];
                if (  LineID < i )
                    rx["LineID"]            =   i-1;
            }
            RadGrid1.Rebind();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_DeleteCommand END.",InputOrderTrace.Sw.Info);
        }

        /// <summary>
        /// Initial insertion of a new line in the order
        /// </summary>
        void RadGrid1_InsertCommand(object source,GridCommandEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_InsertCommand BEG.",InputOrderTrace.Sw.Info);
            GridEditableItem editedItem =   e.Item as GridEditableItem;
            RadComboBox cb              =   ((RadComboBox)editedItem.FindControl("RadComboProduct"));
            string name                 =   cb.Text;
            Guid ProductID              =   (string.IsNullOrEmpty(cb.SelectedValue)) ? Guid.Empty:new Guid(cb.SelectedValue);
            AddOrderItem(makeT,name,ProductID);
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder RadGrid1_InsertCommand END.",InputOrderTrace.Sw.Info);
        }

        void cbProduct_SelectedIndexChanged(object o,RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder cbProduct_SelectedIndexChanged BEG.",InputOrderTrace.Sw.Info);
            RadComboBox comboprod           =   (RadComboBox)o;
            if ( !(comboprod.NamingContainer is GridDataItem ) )
                return;
            string name                     =   comboprod.Text;
            Guid ProductID                  =   new Guid(comboprod.SelectedValue);
            if ( ProductID == Guid.Empty )
                return;
            GridDataItem item               =   (GridDataItem)comboprod.NamingContainer;
            decimal Price                   =   0m;
            Guid uomid                      =   Guid.Empty;
            int nbdecimal                   =   2;
            bool whole                      =   false;
            if ( !GetPrice(ProductID,ref Price,ref uomid,ref nbdecimal,ref whole) )
                return;
            decimal Vat                     =   Settings[AStr.VAT].ToDecimal();
            decimal totVat                  =   Price*Vat/100m;
            RadNumericTextBox tbQuantity    =   (RadNumericTextBox)item.FindControl("TbQuantity");
            tbQuantity.NumberFormat.DecimalDigits   =   (whole) ? 0:2;

            DataTable ordersTable           =   makeT;
            int LineID                      =   (int)RadGrid1.MasterTableView.DataKeyValues[item.ItemIndex]["LineID"];
            DataRow rw                      =   ordersTable.Rows.Find(LineID);
            rw["Product"]                   =   name;
            rw["ProductID"]                 =   ProductID;
            rw["uomid"]                     =   uomid;
            rw["Price"]                     =   Price;
            rw["Quantity"]                  =   1m;
            rw["Discount"]                  =   0m;
            rw["Total"]                     =   Price;
            rw["TotalTaxes"]                =   totVat;
            RadGrid1.Rebind();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder cbProduct_SelectedIndexChanged END.",InputOrderTrace.Sw.Info);
        }

        void tbQuantity_TextChanged(object sender,EventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder tbQuantity_TextChanged BEG.",InputOrderTrace.Sw.Info);
            RadNumericTextBox tbQuantity    =   (RadNumericTextBox)sender;
            if ( !(tbQuantity.NamingContainer is GridDataItem ) )
                return;
            GridDataItem item               =   (GridDataItem)tbQuantity.NamingContainer;
            DataTable ordersTable           =   makeT;
            int LineID                      =   (int)RadGrid1.MasterTableView.DataKeyValues[item.ItemIndex]["LineID"];
            DataRow rw                      =   ordersTable.Rows.Find(LineID);
            decimal quantity                =   (decimal)tbQuantity.DbValue;
            decimal Price                   =   (decimal)rw[ "Price"];
            decimal discount                =   (decimal)rw["Discount"];
            decimal Vat                     =   Settings[AStr.VAT].ToDecimal();
            rw["Quantity"]                  =   quantity;
            decimal total                   =   quantity*Price;
            rw["Total"]                     =   total;
            decimal totVat                  =   (total >= discount) ? (total-discount)*Vat/100m:0m;
            rw["TotalTaxes"]                =   totVat;
            RadGrid1.Rebind();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder tbQuantity_TextChanged END.",InputOrderTrace.Sw.Info);
        }
        
        void tbDiscount_TextChanged(object sender,EventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder tbDiscount_TextChanged BEG.",InputOrderTrace.Sw.Info);
            RadNumericTextBox tbDiscount    =   (RadNumericTextBox)sender;
            if ( !(tbDiscount.NamingContainer is GridDataItem ) )
                return;
            GridDataItem item               =   (GridDataItem)tbDiscount.NamingContainer;
            decimal discount                =   (decimal)tbDiscount.DbValue;
            DataTable ordersTable           =   makeT;
            int LineID                      =   (int)RadGrid1.MasterTableView.DataKeyValues[item.ItemIndex]["LineID"];
            DataRow rw                      =   ordersTable.Rows.Find(LineID);
            rw["Discount"]                  =   discount;
            decimal total                   =   (decimal)rw["Total"];
            decimal Vat                     =   Settings[AStr.VAT].ToDecimal();
            decimal totVat                  =   (total >= discount) ? (total-discount)*Vat/100m:0m;
            rw["TotalTaxes"]                =   totVat;
            RadGrid1.Rebind();
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder tbDiscount_TextChanged END.",InputOrderTrace.Sw.Info);
        }

        #endregion radGrid



        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            clean();
        }

        protected override void OnPreRender(EventArgs e)
        {
            if ( !isTotalTaxesVisible )
                RadGrid1.MasterTableView.GetColumn("TotalTaxes").Visible    =   false;
            if ( !isDiscountVisible)
                RadGrid1.MasterTableView.GetColumn("Discount").Visible      =   false;
            base.OnPreRender(e);
        }
        
        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string loc          =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + loc;
            ResetBtn.SkinID     =   "Reset_" + loc;
        }

        override protected void OnInit(EventArgs e)
        {
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder OnInit BEG.",InputOrderTrace.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( InputOrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputOrder OnInit END.",InputOrderTrace.Sw.Info);
        }

        private void InitializeComponent()
        {
            Load                                    +=  new System.EventHandler(this.Page_Load);
            ADNUpdateModule                         +=  new PortalModuleEventHandler(CrmInputOrder_ADNUpdateModule);
            ResetBtn.Click                          +=  new ImageClickEventHandler(ResetBtn_Click);
            RadGrid1.NeedDataSource                 +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ItemCreated                    +=  new GridItemEventHandler(RadGrid1_ItemCreated);
            RadGrid1.InsertCommand                  +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.DeleteCommand                  +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.ItemDataBound                  +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            // Customers invisibles if autoassigned-> contracts also
            if ( Settings[AStr.AutoCustomer].ToBool() )
            {
                DivComboCustomer.Visible            =   false;
                Label1.Visible                      =   false;
            }
            else
            {
                if ( InputOrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( "[V]CrmInputOrder InitializeComponent setting ComboCustomer.ItemsRequested.",InputOrderTrace.Sw.Info);
                ComboCustomer.EnableLoadOnDemand    =   true;
                ComboCustomer.ItemsRequested        +=  new RadComboBoxItemsRequestedEventHandler(ComboCustomer_ItemsRequested);
            }
            if ( !ShowPriceList )
            {
                PricingChooser.Visible              =   false;
            }
        }

        #endregion Std overrides
    }
}
